/**
 * @html common.multiPopup
 * @description 通用多选弹出框js实现
 * 
 * @since 2011-11-17
 */
Ccay.Module.define("Ccay.Component.MultiPopup", function(page, $S) {

	/**
	 * 多选弹出框页面初始化
	 */
	var servicePath = "";
	var popupBean = "";

	var isInit = true;

	page.init = function(bean, parentContext) {
		$S("#legend_all_title").text($i18n("ccay.popup.label.allTitle"));
		$S("#legend_sel_title").text($i18n("ccay.popup.label.selectTitle"));
		if (typeof bean.condRender == "function") {
			$S("#popup_cond_div").html(bean.condRender())
			$S("#popup_cond_div")
					.append("" +
							"<span id='btn_popup_mutil' class='default ccay-button' onclick='Ccay.Component.MultiPopup.search()'>" +
								"<a class='ccay-icon search'></a>" +
								"<label class='i18n' i18nKey='"+$.i18n.prop("ccay.common.button.search")+"'></label>" +
							"</span>" +
							"<span class='ccay-button' onclick='Ccay.Component.MultiPopup.reset()'>" +
								"<a class='ccay-icon reset'></a>" +
								"<label class='i18n' i18nKey='"+$.i18n.prop("ccay.common.button.clear")+"'></label>" +
							"</span>");
					/*.append("<input id='btn_popup_mutil' type='button' class='default'  onclick='Ccay.Component.MultiPopup.search()'  value='"
							+ $.i18n.prop("ccay.common.button.search")
							+ "' class='button default'>&nbsp;&nbsp;<INPUT  type='button' onclick='Ccay.Component.MultiPopup.reset()' class='button'  value='"+$.i18n.prop("ccay.common.button.clear")+"' />");*/
		} else {
			initConditionArea(bean.columns);
		}
		popupBean = bean;
		servicePath = bean.servicePath;

		if (typeof(bean.initRender) === "function") {
			bean.initRender($S("#popup_cond_div"), self, $S);
		}
		// 将预置条件设置如查询表单中
		if (typeof popupBean.queryParam == "function")
			$S("#popup_cond_div").jsonData(popupBean.queryParam());
		else if(typeof popupBean.queryParam == "object"){
			$S("#popup_cond_div").jsonData(popupBean.queryParam);
		}
		popupBean.defaultParam && $S("#popup_cond_div").jsonData(popupBean.defaultParam);
		initRightTable();
		initLeftTable();
		
		
		$S("fieldSet .gt-freeze-div").delegate("input.gt-f-check","click",function(e){
			var input = $(this);
			setTimeout(function(){
				var record = input.parents(".ccay-grid").getCcayGridManager().activeRecord;
				if(input.is(":checked")){
					choiceRows([record]);
				}else{
					unChoiceRows([record]);
				}
				var allRecord_length = $("#popupLeftTable").getCcayGridManager().getAllRecords().length ,
					checked_length = $("#popupLeftTable_freeze_bodyDiv .gt-f-check:checked").length ;
				allRecord_length !== checked_length && $(".gt-f-totalcheck[name='gt_popupLeftTable_chk_chk']").removeAttr("checked");
			},0)
		})
		
		
		$S("fieldSet .gt-freeze-div").delegate("input.gt-f-totalcheck","click",function(e){
			var input = $(this);
			if(input.attr("name")=="gt_popupLeftTable_chk_chk"){
				if(input.is(":checked")){
					choiceRows($S("#popupLeftTable").getCcayGridManager().dataset.data);
				}else{
					unChoiceRows($S("#popupLeftTable").getCcayGridManager().dataset.data);
				}
			}else{
				unChoiceRows();
				$(".gt-f-totalcheck[name='gt_popupLeftTable_chk_chk']").removeAttr("checked");
			}
		});
		
	};
	
    /*
	  * 替换type='reset' 对initRender出来的combo重置不了
	 */
	page.reset=function(){
		$S("#popupSearchForm").ccayReset();
	}

	page.search = function(model) {
		if ($.isEmptyObject($("#popupSearchForm").jsonData())
				&& (popupBean.allowEmptyCondition === false)) {
			Ccay.UI.showMessage("ccay.popup.label.inputtip", "warn");
			return;
		}
		var leftGrid = $S("#popupLeftTable").getCcayGridManager();
		var pageVO = leftGrid.getPageVO();
		if (model === true) {
			pageVO.curPage = 1;
		}
		var param = $("#popupSearchForm").jsonData();
		if (typeof popupBean.queryParam === "object") {
			param = $.extend({}, popupBean.queryParam, param);
		}else if(typeof popupBean.queryParam === "function"){
			param = $.extend({}, popupBean.queryParam(), param);
		}
		
		var url = servicePath + "/page/" + pageVO.pageSize + "/" + pageVO.curPage
	    Ccay.UI.ajax.getLastRequest($S("#popupLeftTable"), url, param)
		Ccay.doGet(url, param, leftGrid.refresh);
	};

	/**
	 * @description 初始化数据集合grid
	 */
	function initLeftTable() {
		
		var gridOptions = ({
			uniqueField : popupBean.uniqueKey,
			// search:page.search,
			noPage:popupBean.noPage,
			allowPersonalized:false,
			showGridMenu : false ,
			autoLoad : !(popupBean.autoLoad === false),
			toolbarContent : "nav | goto | state",
			width : popupBean.gridWidth || 435,
			onComplete : cynchroLeftTable,
			selectRowByCheck : true,
			pageSize:popupBean.pageSize || Ccay.UI.Config.pager.defaultSize,
			pageSizeList:popupBean.pageSizeList || Ccay.UI.Config.pager.pageSizes,
			allowPersonalized:false,
			columns : [{
						id : 'chk',
						isCheckColumn : true,
						frozen : true
					}].concat(popupBean.columns),
			onRowDblClick : function(value, record,cell,row) {
				//双击选中，再双击取消选中
				var chk = getCheckboxByUniqueKey($S("#popupLeftTable"),record[popupBean.uniqueKey]);
				if(chk.is(":checked")){
					unChoiceRows([record]);
				}else{
					choiceRows([record]);
				}
			},

			operation : {
				search : {
					// 查询条件区域id选择器
					panel : '#popupSearchForm',
					// 查询请求地址
					url : servicePath + "/page/{0}/{1}",
					params : (typeof popupBean.queryParam == "function" ? popupBean.queryParam():popupBean.queryParam) || {}
				}
			},
			pagerOp : {
				mode : null,
				showLast: popupBean.showLast!==false
			}
		});
		if(gridOptions.noPage){
			gridOptions.height=400;
		}
		$S("#popupLeftTable").width(gridOptions.width).ccayGrid(gridOptions);
		$S("#popupLeftTable").tip({
			global:true,
			child : '.gt-body-div .gt-inner',
			tipProp : "tip",
			addTipStyle : false,
			offset:true,
			showOverflow:true,
			width:200
		});
	}

	/**
	 * @description 初始化数据集合grid
	 */
	function initRightTable() {
		var options = {
			uniqueField : popupBean.uniqueKey,
			selectRowByCheck : true,
			width : popupBean.gridWidth || 435,
			height:400,
			allowPersonalized:false,
			showGridMenu : false,
			noPage : true,
			columns : [{
						id : 'chk',
						isCheckColumn : true,
						frozen : true
					}].concat(popupBean.columns),
			onRowDblClick : function(value, record) {
				document.selection && document.selection.clear && document.selection.clear()
				unChoiceRows([record]);
			},
			onComplete : function(){
				var grid = $S("#popupRightTable");
				grid.find("input.gt-f-check").prop("checked",true);
				if(grid.find("tr.gt-row-even").length > 0)
					grid.find("input.gt-f-totalcheck").prop("checked",true);
				else{
					grid.find("input.gt-f-totalcheck").attr("checked",false);
				}
			},
			search : function() {
				var selectedItems = popupBean.selectedItems || [];
				// js中通过分隔符split生产的数组，很有可能导致末尾为空字符，因此判断末尾数组元素是否是空的，是就删除末尾元素
				if (selectedItems.length > 0) {
					if (("" + selectedItems[selectedItems.length - 1]).length == 0) {
						selectedItems.pop();
					}
				}
				if (selectedItems.length == 0) {
					$S("#popupRightTable").getCcayGridManager().refresh();
				} else {
					Ccay.doPost(servicePath, selectedItems,$S("#popupRightTable").getCcayGridManager().refresh,
					function() {
						return true
					});
				}
			}
		};

		$S("#popupRightTable").ccayGrid(options);

	}
	/**
	 * @description 页面初始化或重新查询的时候，通过右边已选数据，初始化左边table的item状态 【checkbox】
	 */
	function cynchroLeftTable() {

		var rightGrid = $S("#popupRightTable").getCcayGridManager();
		var leftGrid = $S("#popupLeftTable").getCcayGridManager();
		selectedRecords = (rightGrid && rightGrid.dataset && rightGrid.dataset.data) || [];
		$.each(selectedRecords, function() {
			this["ccay_popup_selected"] = true;
			var rec = leftGrid.getRecordByUniqueField(this[popupBean.uniqueKey]);
			if (rec) {
				// 如果找到记录，则设置标记为true
				rec["ccay_popup_selected"] = true;
				synchroRow(this[popupBean.uniqueKey],this);
			}
		});
		if($("#popupLeftTable").find("input.gt-f-check:checked").length == leftGrid.getAllRecords().length){ 
		    $("#popupLeftTable").find("input.gt-f-totalcheck").attr("checked","checked"); 
		}
	}

	/**
	 * @description 将已经在右边选中的行给disable掉
	 */
	function synchroRow(key,record) {
		var leftGrid = $S("#popupLeftTable").getCcayGridManager();
		var rows = leftGrid.getAllFreezeRows();
		$.each(rows, function() {
			var rec = leftGrid.getRecordByRow(this);
			if (rec[popupBean.uniqueKey] == key) {
				rec._right = record;
				var chk = $("input.gt-f-check", $(this));
				chk.prop("checked", true);
			}
		})
	}

	/**
	 * @description 点击确认按钮后执行 1 得到popupBean中指定的回调函数的引用。（如果得不到引用则终止该方法） 2
	 *              得到已选项目，此为js对象，通过回调函数的传参返回。
	 */
	page.onOk = function() {

		var flag;
		var rightGrid = $S("#popupRightTable").getCcayGridManager();
		var rowdatas = (rightGrid && rightGrid.dataset && rightGrid.dataset.data) || [];
		if ($.isFunction(popupBean.callback)) {
			flag = popupBean.callback(rowdatas);
		} else {
			Ccay.Core.log("该弹出选择框没有回调方法");
		}
		if (flag !== false)
			page.closeDialog();
		
	};

	/**
	 * @通过 >> 按钮触发，批量选择 rightTable勾选的行
	 */
	function choiceRows(records) {
		var leftGrid = $S("#popupLeftTable").getCcayGridManager(),rightGrid = $S("#popupRightTable").getCcayGridManager();
		records = records || leftGrid.dataset.data;
		// 记录需要选择的记录
		var needSelectRecords = [];
		// 将当中没有选择过的记录放入 needSelectRecords中，并做好标注
		rightGrid.clearCheckedRow = false;
		$.each(records, function() {
			if (!this["ccay_popup_selected"]) {
				needSelectRecords.push(this);
				this["ccay_popup_selected"] = true;
				var chk = getCheckboxByUniqueKey($S("#popupLeftTable"),this[popupBean.uniqueKey]);
				chk.prop("checked", true);
			}
		});
		var recs = $.extend(true, [], needSelectRecords);
		
		rightGrid.addRecords(recs);
		rightGrid.refresh();
	}

	/**
	 * @description 根据grid 对象与 唯一键值，找到checkbox
	 */
	function getCheckboxByUniqueKey(grid, key) {
		return grid.find("input[value='" + key + "'].gt-f-check");
	}

	/**
	 * @通过 << 按钮触发，取消rightTable勾选的行
	 */
	function unChoiceRows(records) {
		var rightGrid = $S("#popupRightTable").getCcayGridManager(),leftGrid = $S("#popupLeftTable").getCcayGridManager();

		$.each(records || leftGrid.dataset.data, function() {
			this["ccay_popup_selected"] = false;
			var rec = leftGrid.getRecordByUniqueField(this[popupBean.uniqueKey]);
			if (rec) {
				rec["ccay_popup_selected"] = false;
				var chk = getCheckboxByUniqueKey($S("#popupLeftTable"),this[popupBean.uniqueKey]);
				chk.removeAttr("checked");
			}
		})
				
		if(records){
			rightGrid.delRecords(records);
			rightGrid.refresh();
		}else{
			rightGrid.refresh([]);
		}
	}

	/**
	 * @description 通过参数动态生成条件区域dom
	 * @param {object[]}
	 *            columns 列参数定义
	 * 
	 */
	function initConditionArea(columns) {
		var hasSearchColumn = false;
		var length = columns.length, autoWidth = true;
		$.each(columns, function(index, column) {
					if (column.isCondition) {
						hasSearchColumn = true;
						$S("#popup_cond_div").append($i18n(column.header) + " ");
						$S("#popup_cond_div")
								.append("<input type='text' style='width:120px' name='"+ column.id + "' maxlength='100'/>&nbsp;");
					}
					if (column.hidden)
						length--;
					if (column.width) {
						autoWidth = false;
					}
				});
		if (length <= 3 && autoWidth) {
			$.each(columns, function() {
						this.width = parseInt(330 / length);
					});
		}
		if (hasSearchColumn)
			$S("#popup_cond_div")
					.append("<span id='btn_popup_mutil' class='default ccay-button' onclick='Ccay.Component.MultiPopup.search(true)'>" +
								"<a class='ccay-icon search'></a>" +
								"<label>"+$.i18n.prop("ccay.common.button.search")+"</label>" +
							"</span>" +
							"<span class='ccay-button' onclick='Ccay.Component.MultiPopup.reset()'>" +
								"<a class='ccay-icon reset'></a>" +
								"<label>"+$.i18n.prop("ccay.common.button.clear")+"</label>" +
							"</span>");
					/*.append("<input type='button' id='btn_popup_mutil' class='button default' onclick='Ccay.Component.MultiPopup.search(true)' value='"
							+ $i18n("ccay.common.button.search")
							+ "' />&nbsp;&nbsp;<INPUT  type='button' onclick='Ccay.Component.MultiPopup.reset()' class='button'  value='"+$.i18n.prop("ccay.common.button.clear")+"' />");*/

	};
});
